from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional

from educate_ai.database import get_db
from educate_ai.papers.paper_schema import PaperCreate, PaperUpdate, PaperOut
from educate_ai.papers.paper_crud import (
    create_paper,
    get_paper,
    get_papers_by_course,
    get_papers_by_major,
    update_paper,
    delete_paper
)

# 创建路由实例
router = APIRouter(
    prefix="/papers",
    tags=["papers"]
)

@router.post("/", response_model=PaperOut, status_code=status.HTTP_201_CREATED)
def create_new_paper(paper: PaperCreate, db: Session = Depends(get_db)):
    """创建新试卷"""
    return create_paper(db=db, paper=paper)

@router.get("/{paper_id}", response_model=PaperOut)
def read_paper(paper_id: int, db: Session = Depends(get_db)):
    """根据ID查询试卷"""
    db_paper = get_paper(db=db, paper_id=paper_id)
    if db_paper is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"ID为 {paper_id} 的试卷不存在"
        )
    return db_paper

@router.get("/course/{course}", response_model=List[PaperOut])
def read_papers_by_course(
    course: str,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """根据课程查询试卷（带分页）"""
    papers = get_papers_by_course(db=db, course=course, skip=skip, limit=limit)
    return papers

@router.get("/major/{major}", response_model=List[PaperOut])
def read_papers_by_major(
    major: str,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """根据专业查询试卷（带分页）"""
    papers = get_papers_by_major(db=db, major=major, skip=skip, limit=limit)
    return papers

@router.put("/{paper_id}", response_model=PaperOut)
def update_existing_paper(
    paper_id: int,
    paper_update: PaperUpdate,
    db: Session = Depends(get_db)
):
    """更新试卷信息"""
    db_paper = update_paper(db=db, paper_id=paper_id, paper_update=paper_update)
    if db_paper is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"ID为 {paper_id} 的试卷不存在"
        )
    return db_paper

@router.delete("/{paper_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_existing_paper(paper_id: int, db: Session = Depends(get_db)):
    """删除试卷"""
    success = delete_paper(db=db, paper_id=paper_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"ID为 {paper_id} 的试卷不存在"
        )
    return None